package com.yequan.thread.cyclicbarrier;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author yq
 * @date 2020/09/04
 */
public class CyclicBarrierDemo5 implements Runnable {

    private ConcurrentHashMap<String, Integer> moneyMap = new ConcurrentHashMap<>();

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(5, this);

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private ExecutorService threadPool = Executors.newFixedThreadPool(5);

    private int sum = 0;

    @Override
    public void run() {
        for (Map.Entry<String, Integer> entry : moneyMap.entrySet()) {
            sum += entry.getValue();
        }
        System.out.println("汇总完成");
        countDownLatch.countDown();
    }

    public void count() {
        for (int i = 0; i < 5; i++) {
            threadPool.submit(() -> {
                try {
                    moneyMap.put(Thread.currentThread().getName(), (int) (Math.random()*10000));
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
    }

    public int getSum() {
        return sum;
    }

    private void await() throws InterruptedException {
        countDownLatch.await();
    }

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrierDemo5 service = new CyclicBarrierDemo5();
        service.count();
        service.await();
        System.out.println("汇总：" + service.getSum());
    }
}
